package com.liuliu.mall.search.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liuliu.mall.common.dto.es.SkuESModel;
import com.liuliu.mall.search.config.MallElasticSearchConfiguration;
import com.liuliu.mall.search.constant.ESConstant;
import com.liuliu.mall.search.service.ElasticSearchSaveService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @program: mall-search
 * @description:
 * @author: wxw
 * @create: 2022-02-21 16:34
 **/
@Service
public class ElasticSearchSaveServiceImpl implements ElasticSearchSaveService {

    @Autowired
    RestHighLevelClient client;

    @Override
    public Boolean productStatusUp(List<SkuESModel> skuESModels) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        for(SkuESModel skuESModel : skuESModels){
            // 绑定索引
            IndexRequest indexRequest = new IndexRequest(ESConstant.PRODUCT_INDEX);
            // 设置ID
            indexRequest.id(skuESModel.getSkuId().toString());
            // 设置文档
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(skuESModel);
            indexRequest.source(json, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }

        BulkResponse bulk = client.bulk(bulkRequest, MallElasticSearchConfiguration.COMMON_OPTIONS);
        boolean b = bulk.hasFailures();
        return !b;
    }
}